﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace YueRu.Common
{
    public class SignHelper
    {
        public static string Md5(string str)
        {
            var sb = new StringBuilder(32);
            MD5 md5 = new MD5CryptoServiceProvider();
            var t = md5.ComputeHash(Encoding.GetEncoding("utf-8").GetBytes(str));
            foreach (var t1 in t)
            {
                sb.Append(t1.ToString("x").PadLeft(2, '0'));
            }
            return sb.ToString();
        }
        /// <summary>
        /// 这个函数有点问题（不要用）
        /// </summary>
        /// <param name="prestr"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string Sign(string prestr, string key)
        {
            var sb = new StringBuilder(32);

            prestr = prestr + key;

            MD5 md5 = new MD5CryptoServiceProvider();
            var t = md5.ComputeHash(Encoding.GetEncoding("utf-8").GetBytes(prestr.ToUpper()));
            foreach (var t1 in t)
            {
                sb.Append(t1.ToString("x").PadLeft(2, '0'));
            }

            return sb.ToString();
        }
        /// <summary>
        /// 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
        /// </summary>
        /// <param name="dicArray">需要拼接的数组</param>
        /// <returns>拼接完成以后的字符串</returns>
        public static string CreateLinkString(SortedDictionary<string, string> dicArray)
        {
            var prestr = new StringBuilder();
            foreach (var temp in dicArray)
            {
                prestr.Append(temp.Key + "=" + temp.Value + "&");
            }

            //去掉最後一個&字符
            var nLen = prestr.Length;
            prestr.Remove(nLen - 1, 1);

            return prestr.ToString();
        }

        /// <summary>
        /// 生成请求时签名
        /// </summary>
        /// <param name="sPara"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string BuildRequestMysign(SortedDictionary<string, string> sPara, string key)
        {
            //把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
            var prestr = CreateLinkString(sPara);
            //把最终的字符串签名，获得签名结果
            var mysign = Md5(prestr + key);
            //var mysign = Sign(prestr, key);

            return mysign;
        }

    }

}
